package com.plian.system.service.yth.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.plian.Tools.CollectionUtil;
import com.plian.Tools.StringUtil;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.entity.im.BaseInvestmentDebt;
import com.plian.system.entity.im.InvestmentDebt;
import com.plian.system.entity.yth.finance.DebtStructure;
import com.plian.system.entity.yth.finance.DebtStructureDetail;
import com.plian.system.mapper.yth.finance.DebtStructureDetailMapper;
import com.plian.system.mapper.yth.finance.DebtStructureMapper;
import com.plian.system.service.yth.IDebtStructureService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author: jatpen
 * @Date: 2023/5/10 3:04 PM
 */
@Service
@Slf4j
public class DebtStructureServiceImpl extends ServiceImpl<DebtStructureMapper, DebtStructure> implements IDebtStructureService {


    @Autowired
    private DebtStructureDetailMapper detailMapper;

    private final String YTH_DATASOURCE_TYPE = "3";



    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
//    @DS("slave_1")
    @Override
    public List<BaseInvestmentDebt> getSyncData(Date startTime, Date endTime) {
        List<BaseInvestmentDebt> baseInvestmentDebtList = new ArrayList<>();

        List<DebtStructure> debtStructures = list(new LambdaQueryWrapper<DebtStructure>()
                .gt(Optional.ofNullable(startTime).isPresent(), DebtStructure::getCreateTime, startTime)
                .le(Optional.ofNullable(endTime).isPresent(), DebtStructure::getCreateTime, endTime));
        if (CollectionUtil.isNotEmpty(debtStructures)) {
            baseInvestmentDebtList = conversion(debtStructures);
        }
        return baseInvestmentDebtList;
    }

    /**
     * 转换对象
     *
     * @param debtStructures
     * @return
     */
    private List<BaseInvestmentDebt> conversion(List<DebtStructure> debtStructures) {

        List<BaseInvestmentDebt> baseInvestmentDebtList = new ArrayList<>();

        List<DebtStructureDetail> structureDetailList = detailMapper.selectList(new LambdaQueryWrapper<DebtStructureDetail>()
                .in(DebtStructureDetail::getDebtStructureId, debtStructures.stream().map(DebtStructure::getId).collect(Collectors.toList())));

        for (DebtStructure debtStructure : debtStructures) {
            BaseInvestmentDebt baseInvestmentDebt = new BaseInvestmentDebt();
            baseInvestmentDebt.setCode(debtStructure.getNumber());
            baseInvestmentDebt.setFilingUnitId(Objects.toString(debtStructure.getReportOrgId(), null));
            baseInvestmentDebt.setDeptId(Objects.toString(debtStructure.getCompetentDeptName(), null));
            baseInvestmentDebt.setFilingMonth(Objects.toString(debtStructure.getYearMonth(), null));
            baseInvestmentDebt.setFormType(String.valueOf(FormTypeConstant.IM_BASE_INVESTMENT_DEBT_FORM));
            baseInvestmentDebt.setStatus(0);
            baseInvestmentDebt.setCreateCompanyId(Objects.toString(debtStructure.getReportOrgId(), null));
            baseInvestmentDebt.setCreateUser(Objects.toString(debtStructure.getReportUserId(), null));
            baseInvestmentDebt.setDataSource(YTH_DATASOURCE_TYPE);
            if (debtStructure.getFinanceReportType()==0){
                baseInvestmentDebt.setType(1);
            }else if (debtStructure.getFinanceReportType()==2){
                baseInvestmentDebt.setType(2);
            }
            baseInvestmentDebt.setDataSourceId(debtStructure.getId().toString());
            //详情
            List<DebtStructureDetail> structureDetails = structureDetailList.stream().filter(e -> e.getDebtStructureId().equals(debtStructure.getId())).collect(Collectors.toList());
            List<InvestmentDebt> investmentDebts = new ArrayList<>();
            structureDetails.forEach(item -> {
                InvestmentDebt investmentDebt = new InvestmentDebt();
                //对应项目信息id
                investmentDebt.setProjectId(item.getDebtProjectId());
                investmentDebt.setProjectNatureId(Objects.toString(item.getProjectNature(), null));
                /**
                 * 从债券项目信息中获取
                 investmentDebt.setProjectName(null);
                 investmentDebt.setProjectCategory(null);
                 investmentDebt.setProjectCompanyId(null);
                 investmentDebt.setIsFundInvestment(null);
                 investmentDebt.setConstructionStatus(null);
                 investmentDebt.setBalancedPlanning(null);
                 investmentDebt.setPlanTotalInvestment(null);
                 investmentDebt.setFiscalFunds(null);
                 investmentDebt.setShareholderCapital(null);
                 investmentDebt.setProjectLoan(null);
                 investmentDebt.setPlanTotalInvestmentSum(null);
                 *
                 */
                investmentDebt.setCompletedProjectsAccounts(StringUtil.isNotBlank(item.getCompleteCount()) ? new BigDecimal(item.getCompleteCount()) : null);
                investmentDebt.setActualFinancialExpenditure(item.getActualFinanceExpend());
                investmentDebt.setActualFiscalFunds(item.getActualFinanceFund());
                investmentDebt.setActualShareholderCapital(item.getActualShareholderFund());
                investmentDebt.setDebtCapitalTotal(item.getTotalDebtFund());
                investmentDebt.setDebtCapitalLoan(item.getActualProjectLoan());
                investmentDebt.setDebtCapitalShareholderAdvance(item.getActualShareholderAdvanceFund());
                investmentDebt.setFutureRaiseDebtAmount(item.getNeedDebtFund());
                investmentDebt.setPresentationCondition(item.getBalancePlanDesc());
                investmentDebt.setIsDeleted(0);
                investmentDebt.setStatus(0);
                investmentDebt.setCreateTime(new Date());
                investmentDebt.setDataSource(YTH_DATASOURCE_TYPE);
                investmentDebt.setDataSourceId(item.getId().toString());
                investmentDebt.setCreateCompanyId(Objects.toString(debtStructure.getReportOrgId(), null));
                investmentDebt.setCreateUser(Objects.toString(debtStructure.getReportUserId(), null));
                investmentDebts.add(investmentDebt);
            });
            baseInvestmentDebt.setInvestmentDebts(investmentDebts);
            baseInvestmentDebtList.add(baseInvestmentDebt);
        }
        return baseInvestmentDebtList;
    }

}
